// 导入数据库
let db = require("../db/index");
//导入bcryptjs加密包
const bcrypt = require("bcryptjs");
// 导入jsonwebtoken 生成JWT字符串（生成token操作）
const jwt = require("jsonwebtoken");
// 导入secret 密钥对象
const config = require("../config");

// 导入发送邮箱模块
const { sendEmail } = require("node-send-email");
const e = require("express");

let code;
// 邮箱验证码
exports.email = async (req, res) => {
    let email = req.body.email;
    let reg = /^[1-9][0-9]{4,10}@qq.com$/;
    if (!reg.test(email)) {
        return res.send({
            s: 400,
            m: "请输入正确的邮箱",
        });
    }
    //...
    code = String(Math.floor(Math.random() * 1000000)).padEnd(6, "0"); //生成随机验证码
    //发送邮件需要的入参
    const params = {
        // 邮箱类型，@qq.com就传qq，@163.com就是传163，不传的话默认为qq
        // 其余类型可以在node_modules/node-send-email/lib/service.js中找到
        type: "qq",
        // 发件人
        name: "测试",
        // 发件箱
        from: "2443408544@qq.com",
        // 发件箱smtp,邮箱—设置–账户–POP3/SMTP服务—开启—获取stmp授权码
        smtp: "fgvibowrnaruecjb",
        // 发送的邮件主题
        subject: "验证码",
        // 收件箱
        to: email,
        // 邮件内容，HTML格式
        html: `
            <p>您好！</p>
            <p>您的验证码是：<strong style="color:orangered;">${code}</strong></p>
            <p>如果不是您本人操作，请无视此邮件</p>
        `,
    };
    await sendEmail(params, (result, info) => {
        if (result) {
            res.send({ s: 200, m: "发送验证码成功" });
        } else {
            res.send({ s: 400, m: "发送验证码失败，请稍后重试" });
        }
    });
};
// 注册
exports.register = (req, res) => {
    let account = req.body.account;
    let passname = req.body.passname;
    let password = req.body.password;
    let eCode = req.body.eCode;
    let user_pic = "user.png";
    let type = req.body.type;
    let id = "u" + Date.now();
    let outside;
    let obj;
    if (type == "b") {
        outside = "backstage_user";
        obj = {
            user_pic,
            account,
            passname,
            s: 1,
        };
        let reg1 = /^\d{11}$/;
        if (!reg1.test(account)) {
            return res.send({
                s: 400,
                m: "请输入11位数的号码",
            });
        }
    } else {
        outside = "user";
        obj = {
            account,
            passname,
            id,
            user_pic,
            essay: "[]",
            concern: "[]",
            likes: "[]",
            collect: "[]",
            comment: "[]",
            fans: "[]",
            s: 1,
        };
        if (eCode != code) {
            console.log(eCode);
            return res.send({
                s: 400,
                m: "验证码错误",
                code,
            });
        }
    }
    let reg2 = /^[a-zA-Z]\w{5,17}$/;
    if (!reg2.test(password)) {
        return res.send({
            s: 400,
            m: "密码必须以字母开头，长度在6~18之间，只能包含字母、数字和下划线",
        });
    }
    // 加密 调用bcrypt.hashSync(明文密码(未加密状态),10(随机盐长度))方法进行加密 返回值加密后的密码
    password = bcrypt.hashSync(password, 10);
    obj.password = password;
    let sql1 = `select * from \`${outside}\` where \`account\` = ?`;
    db.query(sql1, account, (err, data) => {
        if (err) {
            return res.send({
                s: 400,
                m: "操作失败",
            });
        }
        if (data.length > 0) {
            return res.send({
                s: 400,
                m: "账号已存在",
            });
        } else {
            console.log(obj);
            let sql2 = `insert into \`${outside}\` set ?`;
            // let sql2 = `insert into \`${outside}\` (\`account\`,\`passname\`, \`password\`,\`user_pic\`) value (?,?,?,?)`;
            db.query(sql2, obj, (err, data) => {
                if (err) {
                    return res.send({
                        s: 400,
                        m: "注册失败" + err,
                    });
                }
                if (res) {
                    res.send({
                        s: 200,
                        m: "注册成功",
                    });
                }
            });
        }
    });
};
// 登录
exports.signIn = (req, res) => {
    let account = req.query.account;
    let password = req.query.password;
    let type = req.query.type;
    let outside;
    if (type == "b") {
        outside = "backstage_user";
    } else {
        outside = "user";
    }
    let sql1 = `select s,password,passname from \`${outside}\` where \`account\` = ? `;
    db.query(sql1, account, (err, data) => {
        if (err) {
            return res.send({
                s: 400,
                m: "操作失败",
                message: err.message,
            });
        }
        if (data.length == 0) {
            return res.send({
                s: 400,
                m: "无效账号",
            });
        } else {
            if (data[0].s == "1") {
                let status = bcrypt.compareSync(password, data[0].password);
                if (status) {
                    tokenStr = jwt.sign({ account }, config.secretKey, { expiresIn: "24h" });
                    return res.send({
                        s: 200,
                        m: "登录成功",
                        passname: data[0].passname,
                        token: "Bearer " + tokenStr,
                    });
                } else {
                    res.send({
                        s: 400,
                        m: "密码错误",
                    });
                }
            } else {
                res.send({
                    s: 400,
                    m: "该账号违规,已被封禁",
                });
            }
        }
    });
};
// 更改邮箱
exports.setEmail = (req, res) => {
    let nEmail = req.body.nEmail;
    let oEmail = req.body.oEmail;
    let eCode = req.body.code;
    if (nEmail == oEmail) {
        return res.send({
            s: 400,
            m: "请输入新的邮箱号",
        });
    }
    if (eCode != code) {
        return res.send({
            s: 400,
            m: "验证码错误",
            code,
        });
    }
    let sql1 = "select * from user where `account` = ?";
    db.query(sql1, nEmail, (err, data) => {
        if (err) {
            return res.send({
                s: 400,
                m: "修改失败",
            });
        }
        if (data[0]) {
            return res.send({
                s: 400,
                m: "该邮箱已注册",
            });
        } else {
            let sql2 = "UPDATE `user` SET account = ? WHERE account = ?";
            db.query(sql2, [nEmail, oEmail], (err, data) => {
                if (err) {
                    return res.send({
                        s: 400,
                        m: "修改失败",
                    });
                }
                res.send({
                    s: 200,
                    m: "修改成功",
                });
            });
        }
    });
};
// 更改密码
exports.setPassWord = (req, res) => {
    let oPassWord = req.body.oPassWord;
    let nPassWord = req.body.nPassWord;
    let eCode = req.body.code;
    let account = req.body.account;
    if (eCode != code) {
        return res.send({
            s: 400,
            m: "修改失败,验证码错误",
        });
    }
    let sql1 = "select password from `user` where `account` = ?";
    db.query(sql1, account, (err, data) => {
        if (err) {
            return res.send({
                s: 400,
                m: "修改失败",
            });
        }
        let password = data[0].password;
        let status = bcrypt.compareSync(oPassWord, password);
        if (!status) {
            return res.send({
                s: 400,
                m: "修改失败,密码不正确",
            });
        } else {
            let reg2 = /^[a-zA-Z]\w{5,17}$/;
            if (!reg2.test(nPassWord)) {
                return res.send({
                    s: 400,
                    m: "修改失败,密码必须以字母开头，长度在6~18之间，只能包含字母、数字和下划线",
                });
            } else {
                if (oPassWord == nPassWord) {
                    return res.send({
                        s: 400,
                        m: "修改失败,新密码不能与旧密码一致",
                    });
                } else {
                    let sql2 = "UPDATE `user` SET `password`= ? WHERE `account` = ?";
                    nPassWord = bcrypt.hashSync(nPassWord, 10);
                    db.query(sql2, [nPassWord, account], (err, data) => {
                        if (err) {
                            return res.send({
                                s: 400,
                                m: "修改失败",
                            });
                        }
                        return res.send({
                            s: 200,
                            m: "修改成功",
                        });
                    });
                }
            }
        }
    });
};
